// ScholarOne JavaScript Document

//These make the page scroll within the Edit modal to the right section
$("#collapse_editanotherinst").bind('shown', function() {
        document.getElementById('collapse_editanotherinst').scrollIntoView();
});
//Use dropdown to show or hide DIVs. Used on Upload page
$('.drop-down-show-hide').hide();
$('.designationDropdown').change(function () {
    $(this).find("option").each(function () {
        $('#' + this.value).hide();
    });
    $('#' + this.value).show();

});
//This Closes the AuthSearchModal and takes the user to the Author table
$('#AddResultAuthBtn').click(function(){
    $('#AuthSearchModal').modal('hide');
    $(document.body).scrollTop($('#anchorId').offset().top);
});
//This collapses the Colapse Author Add section and scrolls to the author table
$('#AddCreatedAuthBtn').click(function(){
	$('#collapse_author_add').collapse('toggle');
    $(document.body).scrollTop($('#anchorId').offset().top);
});
//This collapses the Colapse Reviewer Add section and scrolls to the author table
$('#AddEditorsBtn').click(function(){
	$('#Collapse_ChooseEditor').collapse('toggle');
    $(document.body).scrollTop($('#anchorId').offset().top);
});
$('#AddNewEditorBtn').click(function(){
	$('#Collapse_ChooseEditor').collapse('toggle');
	$('#collapse_editor_add').collapse('toggle');
    $(document.body).scrollTop($('#anchorId').offset().top);
});

$('#nav-list').scrollspy()
$('#loginbox').scrollspy()
    
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
});
//This is toggling buttons with plus and minus signs
$(".toggleBtn").on('click',function(){
    $(this).children('.icon-minus, .icon-plus, .searchbar').toggleClass("icon-minus icon-plus");
});
//This is for instructions at the top of the steps
$(".morelink").toggle(function(){
    $(this).text("Show less text").siblings(".completetext").show();    
}, function(){
    $(this).text("Read more ...").siblings(".completetext").hide();    
});
//This is for predictive text mockup on Keywords
$('.typeahead').typeahead()

// This closes all popovers if you click everywhere except on a popover; 
$(document).on('mouseup', function(e) {
  if($('.popover').length > 0) {
    $('[data-toggle=popover]:visible').each(function () {
      //the 'is' for buttons that trigger popups
      //the 'has' for icons within a button that triggers a popup
      if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
        $(this).popover('hide');
      }
    });
  }
});

$(document).on('click', '.popover-close-btn, .popover-save-btn', function() {
  var popoverClass = $(this).data('popover-class');
  $('.' + popoverClass).popover('hide');
});

// SF-18576. add tooltips for dropdown items while browsing in IE8
if (typeof $(this) != 'undefined' && this.ie8) {
  $('select option').attr('title', function(index, previousValue) {
    return $(this).text();
  });
}

//show/hide List
    $.fn.showHide = function (options) {
 
    //default vars for the plugin
        var defaults = {
            speed: 1000,
			easing: '',
            changeText: 0,
            showText: '+ Show All',
            hideText: '- Hide All'
 
        };
        var options = $.extend(defaults, options);
 
        $(this).click(function () {
// optionally add the class .toggleDiv to each div you want to automatically close
                      $('.toggleDiv').slideUp(options.speed, options.easing);
             // this var stores which button you've clicked
             var toggleClick = $(this);
             // this reads the rel attribute of the button to determine which div id to toggle
             var toggleDiv = $(this).attr('rel');
             // here we toggle show/hide the correct div at the right speed and using which easing effect
             $(toggleDiv).slideToggle(options.speed, options.easing, function() {
             // this only fires once the animation is completed
             if(options.changeText==1){
             $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
             }
              });
 
          return false;
 
        });
 
    };


   $('.show_hide').showHide({
        speed: 300,  // speed you want the toggle to happen
        easing: '',  //the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
        changeText: 1, // if you dont want the button text to change, set this to 0
        showText: '+ Show Full List',// the button text to show when a div is closed
        hideText: '- Hide Full List' // the button text to show when a div is open
 
    });

// text area special character legacy support formally in basetag.
//TODO: is anything using this?
function insertText(sCode) 
{
  
   if(currentArea != null)  {
    switch(currentAreaType)    {
      case 'Text':
        insertAtCursor(currentArea, sCode); 
        break;
      case 'TextArea':
        insertAtCursor(currentArea, sCode); 
        break;
    }
  }
}
function setArea(current, type)
{
  currentArea = current;  
  currentAreaType = type;  
  
}

var cpos1; 
var lastField1; 
function storeCaret (textEl) {
 if (textEl.createTextRange) 
  {
	if(document.selection)
      selectedRange = document.selection.createRange().duplicate();   
    selectedInputArea = textEl;
  }
}
function insertAtCaret (textEl, text) {
  if (textEl.createTextRange && selectedRange) {
    var caretPos = selectedRange;
    caretPos.text =
      caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?
        text + ' ' : text;
  }
 else {
 textEl.value = text;
 }
}
function checkAreaSet(current, type)
{
  if (currentArea == null) {
    currentArea = current;
    currentAreaType = type;
    if (type == 'TextArea')    {
      storeCaret(current);
    }
  }
  currentArea.focus();
}
function insertAtCursor(myField, myValue) {
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  else if (myField.selectionStart || myField.selectionStart == 0) {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)+myValue
     + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}

// chrome fix for modal dialog
$(document).on('change', '.chrome-select-option-modal-fix', function(){
	var isChrome = window.chrome;
	if(isChrome||isSafari) {
	    if ($(this).val()=='Remove' || $(this).val()=='Edit'){
	        var $optionSelected = $("option:selected", this);
	        var modalName = $optionSelected.attr('href').replace(/[#]/, "");
	        $('#'+modalName).modal('show');
	    }
	}
});

function textLimitRUI(field, maxlen)
{
  var numberOfCRs = field.value.split(/\n/).length - 1; // every line breaks counted as 2 characters CR + LF (minus default)
  if ((trimAll(field.value).length + numberOfCRs) > maxlen) {
   field.value = field.value.substring(0, (maxlen - numberOfCRs));
   //S1MUtils.alert(resources[IResourceName.ALERT], ALERT_TEXT_LIMIT);
  }
}

// **** FIX for issue with not selecting same file again  ****  
  function isSafari(){
	//  return false;
	return window.navigator.vendor.indexOf("Apple")==0 && /\sSafari\//.test(navigator.userAgent);
  }

  function isChrome(){
	// IE11 returns undefined for window.chrome
	var isChromium = window.chrome,
	vendorName = window.navigator.vendor;
	return (isChromium !== null && isChromium !== undefined && vendorName === "Google Inc.");
  }  
		  
  function isIEBrowser(){
	var ua = window.navigator.userAgent;
	var old_ie = ua.indexOf('MSIE ');
	var new_ie = ua.indexOf('Trident/');
	var edge = /Edge\/\d./i.test(navigator.userAgent);
	return (old_ie > -1) || (new_ie > -1) || edge;
  }  

  function isEdge(){
		var edge = /Edge\/\d./i.test(navigator.userAgent);
		return  edge;
	  }  
  function isIE11(){
	  var ua = window.navigator.userAgent;
	  var new_ie = ua.indexOf('Trident/');
	  return (new_ie > -1);
	  
  }
  function resetFileInput($element) {
	if (isChrome() || isIEBrowser() || isSafari()){  
	  $element.val(null);//SF_29009	
	}
  }   
// **** 

// Substring based on bytes 
 function substringInUTF8(str,startInd,  endInd) {
	 var len = Math.min(endInd, str.length-startInd);
     var i, cs, c = 0, bytes = 0;
     for (i = 0; i < len; i++) {
    	 c = str.charCodeAt(i);
         cs = 1;
         if (c >= 128) cs++;
         if (c >= 2048) cs++;
         if (endInd < (bytes += cs)) break;
     }
     return str.substr(startInd, i);
  }
//Affix issue
 $(function () {
   $('#navigationDIV').each(function(){
     var fromTop = $(this).offset().top;
     var stopOn = $('#contentSectionDIV').height() - $('.footer_wrapper').offset().top + ($(this).outerHeight() - $(this).height());
     $(this).affix({
       offset: {
         top: fromTop,
         bottom: stopOn
       }
     });
   });
 });
 
 function copyToClipbaord(text, message, newUI)
 {
 	 if(text.length === 0)
 		 return false;
 	 if (window.clipboardData && window.clipboardData.setData) 
 	 {
 		// Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
 	    var successful = clipboardData.setData("Text", text);
 	    if(successful)
 	    	alert(message); 
 	 }
 	 else if (document.queryCommandSupported && document.queryCommandSupported("copy")) 
 	 {
         var textarea = document.createElement("textarea");
         textarea.textContent = text;
         textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
         document.body.appendChild(textarea);
         textarea.select();
         try {
             var successful = document.execCommand("copy");  // Security exception may be thrown by some browsers.
             if(successful&&newUI)
             {	 
            	 $('#alertModal > div.modal-header > h3 > i').hide();// It hides exclamation mark(!) from upper right corner of alert popup
            	 S1MUtils.alert(null,message); 
             }
      	     else if(successful&&!newUI)	
      	    	 alert(message); 
             }
         catch (ex) {
             console.warn("Copy to clipboard failed.", ex);
             return false;
         }
         finally {
             document.body.removeChild(textarea);
         }
      }
 }

 function printAnalysisPop() {
 	if($('#pdfProofExcl').length)
 {	
 		$('#pdfProofExcl').printThis();
 		
 } else {
	 	$('#accordion').printThis();
 }
}
 
$(document).ready(function(){
	// S1M-7454 / 7458 / 7461
	
	$("[role=button]").focus(function(){
		$(this).attr("hidefocus","false");
	    $(this).css("outline", "2px solid #333333");	    
	});
	$("[role=button]").blur(function(){
	    $(this).css("outline", "none");	  
	    $(this).attr("hidefocus","true");  
	});
	 		
});

	